//  Android Carpool System
//  2011-2011
//  Author: Jinhuan Wang
//  name: Convert.java
//  description: provide some static methods to convert data from object to xml string and xml to object
//$history: /carpool/scr/com/dataexchange/Convert.java$
package com.carpool.message;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.google.android.maps.GeoPoint;

public class Convert {
	public static StringBuffer reguest(RequestMessage m_postData) {
		StringBuffer stringbuffer = new StringBuffer("<?xml version=\"1.0\"?>");
		if (m_postData.getPostType() == true) {

			p2sRequest t_p = (p2sRequest) m_postData;
			stringbuffer.append("<Pdata>");
			stringbuffer.append("<userID>");
			stringbuffer.append(Integer.toString(t_p.getUserID()));
			stringbuffer.append("</userID>");
			stringbuffer.append("<startPoint>");
			stringbuffer.append("<longitude>");
			stringbuffer.append(Integer.toString(t_p.getStartPoint()
					.getLongitudeE6()));
			stringbuffer.append("</longitude>");
			stringbuffer.append("<latitude>");
			stringbuffer.append(Integer.toString(t_p.getStartPoint()
					.getLatitudeE6()));
			stringbuffer.append("</latitude>");
			stringbuffer.append("</startPoint>");
			stringbuffer.append("<endPoint>");
			stringbuffer.append("<longitude>");
			stringbuffer.append(Integer.toString(t_p.getEndPoint()
					.getLongitudeE6()));
			stringbuffer.append("</longitude>");
			stringbuffer.append("<latitude>");
			stringbuffer.append(Integer.toString(t_p.getEndPoint()
					.getLatitudeE6()));
			stringbuffer.append("</latitude>");
			stringbuffer.append("</endPoint>");
			stringbuffer.append("<period>");
			stringbuffer.append(t_p.getDate().toString());
			stringbuffer.append("</period>");
			stringbuffer.append("</Pdata>");
		} else {
			d2sRequest t_d = (d2sRequest) m_postData;
			stringbuffer.append("<Ddata>");
			stringbuffer.append("<userID>");
			stringbuffer.append(Integer.toString(t_d.getUserID()));
			stringbuffer.append("</userID>");
			stringbuffer.append("<totalDistance>");
			stringbuffer.append(t_d.getTotalDistance());
			stringbuffer.append("</totalDistance>");
			stringbuffer.append("<requirement>");
			stringbuffer.append(t_d.getRequirement());
			stringbuffer.append("</requirement>");
			stringbuffer.append("<capacity>");
			stringbuffer.append(Integer.toString(t_d.getCapacity()));
			stringbuffer.append("</capacity>");
			stringbuffer.append("<GeoPoints>");
			List<MyGeoPoint> mp = t_d.getMyGeoPoints();
			for (int i = 0; i < mp.size(); i++) {
				stringbuffer.append("<Point>");
				stringbuffer.append("<longitude>");
				stringbuffer.append(Integer.toString(mp.get(i).getPoint()
						.getLongitudeE6()));
				stringbuffer.append("</longitude>");
				stringbuffer.append("<latitude>");
				stringbuffer.append(Integer.toString(mp.get(i).getPoint()
						.getLatitudeE6()));
				stringbuffer.append("</latitude>");
				stringbuffer.append("<period>");
				stringbuffer.append(mp.get(i).getDate().toString());
				stringbuffer.append("</period>");
				stringbuffer.append("</Point>");
			}
			stringbuffer.append("</GeoPoints>");
			stringbuffer.append("</Ddata>");
		}
		return stringbuffer;
	}

	public static ReplyMessage receive(DataInputStream dis) {
		DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
		ReplyMessage message =null;
		try {
			DocumentBuilder db = fac.newDocumentBuilder();
			Document doc = db.parse(dis);
			NodeList typeNodeList=doc.getElementsByTagName("type");
			Element typeElement = (Element)typeNodeList.item(0);
			NodeList textList = typeElement.getChildNodes();
			String s= textList.item(0).getNodeValue().trim();
			String e2sp=MessageType.passager_reply.toString();
			String e2sd=MessageType.driver_reply.toString();
				if(s.equals(e2sd))
				{
					
					 message=parseS2DReply(doc);
				}
				else if(s.equals(e2sp))
				{
					
					 message=parseS2PReply(doc);
				}
		}catch(Exception e)
		{
			
		}
			return  message;
			
	}
	private static ReplyMessage parseS2PReply(Document doc) {
		
		s2pReply message=new s2pReply();
		NodeList routelist= doc.getElementsByTagName("route");
		for(int i=0;i<routelist.getLength();i++)
		{
			RouteInfo routeInfo=new RouteInfo();
			Node pnode=routelist.item(i);//router
			NodeList routeChildNode=pnode.getChildNodes();
			for(int j=0;j<routeChildNode.getLength();j++)
			{
				Node node=routeChildNode.item(j);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					if (node.getNodeName().equals("DriveCellphone")) {
						routeInfo.setNumber(node.getFirstChild()
								.getNodeValue());
						continue;
					}
					if (node.getNodeName().equals("RouteID")) {
						routeInfo.setRouteID(Integer.parseInt(node.getFirstChild()
								.getNodeValue()));
						continue;
					}
					if (node.getNodeName().equals("DriveID")) {
						routeInfo.setDriverID(Integer.parseInt(node.getFirstChild()
								.getNodeValue()));
						continue;
					}
					if (node.getNodeName().equals("username")) {
						routeInfo.setUsername(node.getFirstChild()
								.getNodeValue());
						continue;
					}
					if (node.getNodeName().equals("credit")) {
						routeInfo.setCredit(Integer.parseInt(node
								.getFirstChild().getNodeValue()));
						continue;
					}
					if (node.getNodeName().equals("requirement")) {
						routeInfo.setRequirement(node
								.getFirstChild().getNodeValue());
						continue;
					}
					if (node.getNodeName().equals("remainder")) {
						routeInfo.setRemainder(Integer
								.parseInt(node.getFirstChild()
										.getNodeValue()));
						continue;
					}
					if (node.getNodeName()
							.equals("CloseStratpoint")) {
						int longitude = 0;
						int latitude = 0;
						NodeList slist = node.getChildNodes();
						for (int k = 0; k < slist.getLength(); k++) {
							Node snode = slist.item(k);
							if (snode.getNodeType() == Node.ELEMENT_NODE) {
								if ("longitude".equals(snode
										.getNodeName())) {
									longitude = Integer
											.parseInt(snode
													.getFirstChild()
													.getNodeValue());
									continue;
								}
								if ("latitude".equals(snode
										.getNodeName())) {
									latitude = Integer
											.parseInt(snode
													.getFirstChild()
													.getNodeValue());
									continue;
								}
							}
						}
						routeInfo.setCStartPoint(latitude,
								longitude);
						continue;
					}
					if (node.getNodeName().equals("CloseEndpoint")) {
						int longitude = 0;
						int latitude = 0;
						NodeList slist = node.getChildNodes();
						for (int k = 0; k < slist.getLength(); k++) {
							Node snode = slist.item(k);
							if (snode.getNodeType() == Node.ELEMENT_NODE) {
								if ("longitude".equals(snode
										.getNodeName())) {
									longitude = Integer
											.parseInt(snode
													.getFirstChild()
													.getNodeValue());
									continue;
								}
								if ("latitude".equals(snode
										.getNodeName())) {
									latitude = Integer
											.parseInt(snode
													.getFirstChild()
													.getNodeValue());
									continue;
								}
							}
						}
						routeInfo.setCEndPoint(latitude, longitude);
						continue;
					}
				}
			
			}
			message.addRouter(routeInfo);
		}
		return message;
	}

	private static ReplyMessage parseS2DReply(Document doc) {
		NodeList statelist= doc.getElementsByTagName("state");
		s2dReply message=new s2dReply();
		State state = (State) Enum.valueOf(State.class, statelist.item(0).getFirstChild().getNodeValue());														
		message.setState(state);
		return message;
	}

	public static List<GeoPoint> parseAddress(View textEntryView, int Id,Context context) {
		Geocoder geocoder = new Geocoder(context);
		EditText v = (EditText) textEntryView.findViewById(Id);
		String staddress = v.getText().toString();
		List<Address> address;
		List<GeoPoint> addresspoint = new ArrayList<GeoPoint>();
		try {
			address = geocoder.getFromLocationName(staddress, 5);

			for (int i = 1; i <= address.size(); i++) {
				Address location = address.get(i - 1);
				double lat = location.getLatitude();
				double lon = location.getLongitude();
				GeoPoint p1 = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
				addresspoint.add(p1);
				// Toast.makeText(this, "success", 20).show();

			}
		} catch (IOException e) {
			Log.e("IOException", e.getMessage());
			// Toast.makeText(this, "IOException:  " + e.getMessage(),
			// 20).show();
		}

		return addresspoint;
	}
//	public static String parseCoords(GeoPoint point,Context context){
//		Geocoder geocoder = new Geocoder(context);
//		String result=null;
//		try{
//			List<Address> address=geocoder.getFromLocation(point.getLatitudeE6()/1000000.0, point.getLongitudeE6()/1000000.0, 1);
//			result=address.get(0).toString();
//		}catch(Exception e){}
//		
//		return result;
//	}
}
